package com.java.star.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.star.novel.core.bean.Result;
import com.java.star.novel.core.enums.ResultCode;
import com.java.star.novel.entity.*;
import com.java.star.novel.mapper.NovelMapper;
import com.java.star.novel.no.to.PageTO;
import com.java.star.novel.no.to.SearchTO;
import com.java.star.novel.no.vo.NovelVO;
import com.java.star.novel.service.*;
import com.java.star.novel.vo.NovelTable;
import com.java.star.novel.vo.SearchNovelTable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 小说表 服务实现类
 * </p>
 *
 * @author 零限Lx
 * @since 2023-07-13
 */
@Service
public class NovelServiceImpl extends ServiceImpl<NovelMapper, Novel> implements NovelService {

    @Autowired
    NovelMapper novelMapper;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AuthorService authorService;
    @Autowired
    NovelService novelService;

    @Override
    public List<Novel> getIndexTitleBlockNovel_LX() {

        return null;
    }
    @Autowired
    private BlockShowNovelService blockShowNovelService;


    @Override
    public List<Novel> getIndexSideshowNovel_XL() {
        // List<Novel> novelList = blockShowNovelService.lambdaQuery()
        //         .eq(BlockShowNovel::getType, 0)
        //         .orderByAsc(BlockShowNovel::getSort).last("limit 4").list()
        //         .stream().map(blockShowNovel -> getById(blockShowNovel.getNovelId()))
        //         .collect(Collectors.toList());

        List<Long> novelIds = blockShowNovelService.lambdaQuery()
                .eq(BlockShowNovel::getType, 0)
                .orderByAsc(BlockShowNovel::getSort)
                .last("limit 4").list()
                .stream().map(BlockShowNovel::getNovelId).collect(Collectors.toList());

        Map<Long, Novel> novelMap = lambdaQuery().in(Novel::getId, novelIds).list()
                .stream().collect(Collectors.toMap(Novel::getId, novel -> novel));

        List<Novel> novelList = novelIds.stream().map(novelId -> novelMap.get(novelId))
                .collect(Collectors.toList());

        return novelList;
    }


    @Autowired
    private IndexRecommendService indexRecommendService;
    /*接口6.1*/
    @Override
    public List<Novel> getWeekRecommendNovel() {
        List<IndexRecommend> indexRecommendList = indexRecommendService.lambdaQuery()
                .eq(IndexRecommend::getType, 0)
                .orderByAsc(IndexRecommend::getSort)
                .last("LIMIT 6")
                .list();

        if (indexRecommendList.isEmpty()) {
            return null;
        }

        List<Long> novelIdList = indexRecommendList.stream()
                .map(IndexRecommend::getNovelId)
                .collect(Collectors.toList());

        QueryWrapper<Novel> novelQueryWrapper = new QueryWrapper<>();
        novelQueryWrapper.in("id", novelIdList);
        return this.list(novelQueryWrapper);
    }

    @Override
    /*接口6.2*/
    public List<NovelVO> getHotRecommendNovel() {
        // 查询novel_index_recommend表中类型为热门推荐的记录，并按sort升序排序，限制6条
        List<IndexRecommend> indexRecommendList = indexRecommendService.lambdaQuery()
                .eq(IndexRecommend::getType, 1)
                .orderByAsc(IndexRecommend::getSort)
                .last("LIMIT 6")
                .list();

        if (indexRecommendList.isEmpty()) {
            return Collections.emptyList();
        }

        // 获取热门推荐小说的id集合
        List<Long> novelIdList = indexRecommendList.stream()
                .map(IndexRecommend::getNovelId)
                .collect(Collectors.toList());

        // 根据小说id集合查询对应的小说信息
        List<Novel> novelList = this.listByIds(novelIdList);

        // 假设您已经获取了所有作者的笔名，并以Map<Long, String>的形式存储，其中key为作者ID，value为笔名
        Map<Long, String> penNameMap = getPenNameMap();

        // 将查询到的Novel列表转换为NovelVO列表，并设置penName字段的值
        List<NovelVO> novelVOList = novelList.stream().map(novel -> {
            NovelVO novelVO = new NovelVO();
            BeanUtils.copyProperties(novel, novelVO);
            novelVO.setPenName(penNameMap.get(novel.getAuthorId()));
            return novelVO;
        }).collect(Collectors.toList());

        return novelVOList;
    }

    // 假设有一个获取作者ID和笔名的方法
    private Map<Long, String> getPenNameMap() {
        // 有如下的作者ID和笔名的映射数据
        Map<Long, String> penNameMap = new HashMap<>();
        penNameMap.put(1L, "张三");
        penNameMap.put(2L, "李四");
        penNameMap.put(3L, "王五");
        return penNameMap;

    }
    /*接口6.3*/
    @Override
    public List<NovelVO> getQualityRecommendNovel() {
        // 查询novel_index_recommend表中类型为精品推荐的记录，并按sort升序排序，限制6条
        List<IndexRecommend> indexRecommendList = indexRecommendService.lambdaQuery()
                .eq(IndexRecommend::getType, 2)
                .orderByAsc(IndexRecommend::getSort)
                .last("LIMIT 6")
                .list();

        if (indexRecommendList.isEmpty()) {
            return Collections.emptyList();
        }

        // 获取热门推荐小说的id集合
        List<Long> novelIdList = indexRecommendList.stream()
                .map(IndexRecommend::getNovelId)
                .collect(Collectors.toList());

        // 根据小说id集合查询对应的小说信息
        List<Novel> novelList = this.listByIds(novelIdList);

        // 假设您已经获取了所有作者的笔名，并以Map<Long, String>的形式存储，其中key为作者ID，value为笔名
        Map<Long, String> penNameMap = getPenNameMap();

        // 将查询到的Novel列表转换为NovelVO列表，并设置penName字段的值
        List<NovelVO> novelVOList = novelList.stream().map(novel -> {
            NovelVO novelVO = new NovelVO();
            BeanUtils.copyProperties(novel, novelVO);
            novelVO.setPenName(penNameMap.get(novel.getAuthorId()));
            return novelVO;
        }).collect(Collectors.toList());

        return novelVOList;
    }

    @Override
    public List<Novel> recommended(int novelId, int categoryId) {
        List<Novel> novelList = novelMapper.recommended(novelId,categoryId);
        return novelList;
    }

    @Override
    public Result publishNovel(Novel novel) {
        String title = novel.getTitle();
        Long authorid = 110L;
        LambdaQueryWrapper<Novel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Novel::getTitle,title);
        Novel one = novelMapper.selectOne(queryWrapper);
        if (one != null){
            return Result.fail().code(ResultCode.REPEAT);
        }
        novel.setAuthorId(authorid);
        novel.setPublishState(0);
        novel.setNewestChapterId(1L);
        novel.setCommentCount(0);
        novel.setChapterTotalCount(0);
        int insert = novelMapper.insert(novel);
        if (insert <= 0){
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public SearchNovelTable searchNovelTable(SearchTO searchTO, PageTO page) {
        Integer currentPage = page.getCurrentPage();
        Integer pageSize = page.getPageSize();
        String authorName = searchTO.getAuthorName();
        String bookName = searchTO.getBookName();
        Integer categoryId = searchTO.getCategoryId();

        SearchNovelTable searchNovelTable = new SearchNovelTable();
        Page<Novel> pageInfo = new Page<>(currentPage,pageSize);

        Long authorId = null;
        LambdaQueryWrapper<Author> autowiredLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (authorName != null && authorName != ""){
            autowiredLambdaQueryWrapper.eq(Author::getPenName,authorName);
            Author author = authorService.getOne(autowiredLambdaQueryWrapper);
            authorId = author.getId();
        }

        LambdaQueryWrapper<Novel> queryWrapper = new LambdaQueryWrapper<>();
        if (bookName != null && bookName != ""){
            queryWrapper.eq(Novel::getTitle,bookName);
        }
        if (authorId != null){
            queryWrapper.eq(Novel::getAuthorId,authorId);
        }
        if (categoryId != null){
            queryWrapper.eq(Novel::getCategoryId,categoryId);
        }
        List<Novel> novelLists = novelService.list(queryWrapper);
        novelService.page(pageInfo,queryWrapper);

        List<NovelTable> novelTables = new ArrayList<>();
        for (Novel novel : pageInfo.getRecords()) {
            NovelTable novelTable = new NovelTable();
            BeanUtils.copyProperties(novel,novelTable);
            Integer categoryId1 = novel.getCategoryId();
            Long authorId1 = novel.getAuthorId();
            Category byId = categoryService.getById(categoryId1);
            String categoryName = byId.getCategoryName();
            novelTable.setCategoryName(categoryName);
            Author authorById = authorService.getById(authorId1);
            String penName = authorById.getPenName();
            novelTable.setPenName(penName);
            novelTables.add(novelTable);
        }

        int size = novelLists.size();
        searchNovelTable.setNovelTables(novelTables);
        searchNovelTable.setTotal(size);

        /*for (Novel novel : novelList) {
            NovelTable novelTable = new NovelTable();
            BeanUtils.copyProperties(novel,novelTable);
            Integer categoryId1 = novel.getCategoryId();
            Long authorId1 = novel.getAuthorId();
            Category byId = categoryService.getById(categoryId1);
            String categoryName = byId.getCategoryName();
            novelTable.setCategoryName(categoryName);
            Author authorById = authorService.getById(authorId1);
            String penName = authorById.getPenName();
            novelTable.setPenName(penName);
            novelTables.add(novelTable);
        }*/
        return searchNovelTable;
    }

}
